# -*- coding:utf-8 -*-
"""
作者：MySoul
日期：2023年10月20日
"""
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

from pojo.Status import state
from service import ConfigService, LogRecoderService
from utils import Util


def __sendContent(config_service, contentText):
    """
    推送指定消息到邮件
    :param contentText: 邮件内容
    :return:
    """
    # 1.发送邮件预处理
    LogRecoderService.logger.info("正在发送邮件……")

    # 2.读取邮件信息
    smtp_server = ConfigService.get_config(config_service, 'email', 'smtp_server')  # 邮件服务器
    smtp_port = ConfigService.get_config(config_service, 'email', 'smtp_port')  # 邮件服务端口
    sender_email = ConfigService.get_config(config_service, 'email', 'sender_email')  # 发送者邮件
    sender_pwd = ConfigService.get_config(config_service, 'email', 'sender_pwd')  # 发送者授权码
    receiver_email = ConfigService.get_config(config_service, 'email', 'receiver_email')  # 接收者邮件
    subject = ConfigService.get_config(config_service, 'email', 'subject')  # 邮件主题

    # 3.创建邮件对象
    msg = MIMEText(contentText)
    msg['Subject'] = subject
    msg['From'] = formataddr(("智慧管理助手", sender_email))
    msg['To'] = receiver_email
    smtp = smtplib.SMTP(smtp_server, int(smtp_port))

    # 4.发送邮件
    try:
        smtp.login(sender_email, sender_pwd)
        # 发送邮件
        smtp.sendmail(sender_email, receiver_email, msg.as_string())
        LogRecoderService.logger.info("邮件推送成功~")
    except Exception as e:
        tips = "邮件发送失败！！详细查看error.txt文件！！"
        LogRecoderService.logger.error(tips)
        Util.write_error_file(ConfigService.get_config(config_service, 'script', 'error_path'), e)
        return state.error
    finally:
        smtp.quit()
    return state.success


def check_and_send_message(config_service):
    """
    检查并推送错误消息
    :param config_service:
    """
    # 1.检查日志中是否有error.txt文件
    hasError = Util.getFileStatus(f"{ConfigService.get_config(config_service, 'script', 'error_path')}error.txt")
    try:
        # 2.存在，则推送error.txt中信息
        if hasError:
            # 2.1获取error.txt中的信息
            contentText = Util.getFileContent(
                f"{ConfigService.get_config(config_service, 'script', 'error_path')}error.txt")
            # 2.2推送error.txt中的信息
            rspCode = __sendContent(config_service, contentText)
            # 2.3推送成功，则删除error.txt文件
            if rspCode == state.success:
                Util.removeFile(f"{ConfigService.get_config(config_service, 'script', 'error_path')}error.txt")
            # 2.4推送失败，则记录日志
            else:
                LogRecoderService.logger.warning("邮件推送失败，请查明原因！")
                pass
        else:
            # 3.不存在，则跳过
            pass
    except Exception as e:
        LogRecoderService.logger.error(e)


if __name__ == '__main__':
    pass
